package com.len.controller;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeWapPayModel;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import com.len.base.BaseController;
import com.len.base.CurrentUser;
import com.len.entity.SpGoods;
import com.len.entity.SpOrder;
import com.len.entity.SysUser;
import com.len.service.SpGoodsService;
import com.len.service.SpOrderService;
import com.len.service.SpYongjinService;
import com.len.service.SysUserService;
import com.len.util.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Timestamp;
import java.util.*;

import static cn.hutool.core.util.StrUtil.uuid;

@RestController
@RequestMapping("order")
public class SpOrderController extends BaseController<SpOrder> {
    @Autowired
    private SpOrderService spOrderService;
    @Autowired
    private SpGoodsService spGoodsService;
    @Autowired
    private SpYongjinService spYongjinService;
    @Autowired
    private SysUserService userService;
    @Autowired
    private UploadUtil uploadUtil;
    @GetMapping(value = "/showOrders")
    public ModelAndView showUser(Model model) {
        ModelAndView modelAndView= new ModelAndView("/order/orderList");
        return modelAndView;
    }
    @RequestMapping("/show")
    public ModelAndView show(Model model,String id){
        SpOrder so = spOrderService.queryById(id);
        SpGoods sp = spGoodsService.selectId(so.getTbGoodsid());
        so.setTbGoodsid(sp.getTbGoodsName());
        model.addAttribute("so",so);
        ModelAndView modelAndView= new ModelAndView("/order/order-detail");
        return modelAndView;
    }
    @GetMapping(value = "/showall")
    @ResponseBody
    public ReType showall(Model model, SpOrder spOrder, String page, String limit){
        return spOrderService.selectDataByPage(spOrder,Integer.valueOf(page), Integer.valueOf(limit));
    }
    /**
     * 实名认证
     */
    @PostMapping("/sfz")
    public Map sfz (String username,String idcard){

        CurrentUser user = CommonUtil.getUser() ;
        spOrderService.updateUser(username,idcard,user.getId());
        Map map = new HashMap();
        return map;
//        return spOrderService.UpAddress(name,phone,region,detailedAddress,postalCode,user.getUsername());
    };
    /**
     * 实名认证
     */
    @PostMapping("/regis")
    public Map regis (String username,String password,String invite){
        password = Md5Util.getMD5(username,password);
        SysUser user = userService.selectByPrimaryKey(invite);
        String num = user.getTB_JSPERSON();
        int numInt = Integer.valueOf(num);
        numInt = numInt+1;
        SysUser user1 = new SysUser();
        user1.setId(uuid());
        user1.setUsername(username);
        user1.setPassword(password);
        user1.setTB_JSPERSON(String.valueOf(numInt));
        user1.setJSR(invite);
        spOrderService.insertUser(user1);
        Map map = new HashMap();
        map.put("success",true);
        return map;
    };
    /**
     * 我的地址
     */
    @PostMapping("/getPerson")
    public Map getPerson (){
        CurrentUser user = CommonUtil.getUser() ;
        Map map = spOrderService.getPerson(user.getId());
        return map;
//        return spOrderService.UpAddress(name,phone,region,detailedAddress,postalCode,user.getUsername());
    };
//    @PostMapping("/changepwd")
//    @ResponseBody
//    public Map changepwd(String changepwd){
//        CurrentUser user = CommonUtil.getUser() ;
//        user.setPassword(changepwd);
//        changepwd = Md5Util.getMD5(changepwd, user.getUsername());
//        spOrderService.changePwd(user.getId(),changepwd);
//        Map map = new HashMap();
//        map.put("success",true);
//        return map;
//    }
    /**
     * 加锁生成订单
     * @param ID 商品ID
     * @return
     */
    @RequestMapping("/save")
    public synchronized Map save(String ID, String TB_GOODSTO){
        Map jsonUtil = new HashMap<String,String >();
        jsonUtil.put("success",true);
        try {
            //库存是否为0,为零时，提示已经售空
            if(spGoodsService.exit(ID)){
                jsonUtil.put("msg","已售空");
                return jsonUtil;
            }
            CurrentUser user = CommonUtil.getUser();
            Double price =  user.getTB_BZJ_PRICE();
            if(StringUtils.isEmpty(String.valueOf(price))){
                jsonUtil.put("msg","请先交保证金");
                return jsonUtil;
            }
            SpGoods spGoods =  spGoodsService.selectId(ID);
            //商品数量-1
            spGoodsService.changeNum(ID);
            SpOrder spOrder = new SpOrder();
            spOrder.setId(uuid());
            spOrder.setTbGoodsid(ID);
            spOrder.setTbAddtime(new Date());
            spOrder.setTbBuyer(CommonUtil.getUser().getUsername());
            spOrder.setTbFilePath(spGoods.getTbGoodsPath());
            spOrder.setTbGoodsState(spGoods.getTbGoodsState());
            spOrder.setTbNumber(uuid());
            spOrder.setTbOrderState(1);
            spOrder.setTbPrice(spGoods.getTbGoodsPrice());
            spOrder.setTbSeller(TB_GOODSTO);
            spOrderService.insert1(spOrder);

            String gmcs = user.getGmcs();
            if(StringUtils.isNotEmpty(gmcs)){
                int  cd = Integer.valueOf(gmcs);
                cd =cd-1;
                gmcs = String.valueOf(cd);
            }
            spOrderService.subgmcs(gmcs,user.getId());
        }catch (Exception e){
            e.printStackTrace();
        }
        jsonUtil.put("msg","成功");
        return jsonUtil;
    }


    @RequestMapping("/changepwd")
    @ResponseBody
    public String changepwd(String  password,String oldPassword){
        String userName = CommonUtil.getUser().getUsername();
        //原密码
        String paswd = CommonUtil.getUser().getUsername();
        //验证
        String pas = Md5Util.getMD5(userName,oldPassword);
        String id = CommonUtil.getUser().getId();
        if(pas.equals(paswd)){
            String newpas = Md5Util.getMD5(userName,password);
            spOrderService.changePwd(newpas,id);
        }
        return "成功";
    }



    @RequestMapping("/update")
    public String update(SpOrder spOrder){
        try {
            spOrderService.updateByPrimaryKey(spOrder);
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }
    /**
     * 查看所有订单
     * @return
     */
    @RequestMapping("showll")
    @ResponseBody
    public List<SpOrder> show(){
        CurrentUser user = CommonUtil.getUser() ;
        List<SpOrder>  spOrder=  (List<SpOrder>) spOrderService.showll(user.getId());
        return spOrder;

    }


    /**\
     * 买单卖单数量
     * @return
     */

    @RequestMapping("showNumber")
    @ResponseBody
    public Map showNumber(String state){
        List<SpOrder>  spOrder = null;
               CurrentUser user = CommonUtil.getUser() ;
        Integer buy_count  = spOrderService.showTB_BUYER(user.getUsername());
        Integer sell_count  = spOrderService.showTB_SELLER(user.getUsername());
        Map data = new HashMap();
        data.put("BUY_COUNT",buy_count);
        data.put("SELL_COUNT",sell_count);
        return data;
    }
    /**\
     * 买单卖单数据
     * @return
     */

    @RequestMapping("showMyOrder")
    @ResponseBody
    public  List<Map>  showMyOrder(String state){
        CurrentUser user = CommonUtil.getUser();
        String name = user.getUsername();
        List<Map>   spOrder = null;
//                CurrentUser user = CommonUtil.getUser() ;
        if (state=="我的买单"||state.equals("我的买单")){
            spOrder= spOrderService.showDataTB_BUYER(user.getUsername());
        }
        if (state=="我的卖单"||state.equals("我的卖单")){
            spOrder =spOrderService.showDataTB_SELLER(user.getUsername());
        }
        if (state=="全部订单"||state.equals("全部订单")){
            spOrder =spOrderService.showData(user.getUsername());
        }
        if (state=="委托代卖费"||state.equals("委托代卖费")){
            spOrder =spOrderService.showZfcg(user.getUsername());
        }
        if (state=="历史交易"||state.equals("历史交易")){
            spOrder =spOrderService.showJycg(user.getUsername());
        }
        if (state=="确认收货"||state.equals("确认收货")){
            spOrder =spOrderService.showQrsh(user.getUsername());
        }
        for (Map map : spOrder){
            map.put("user",name);
        }
        return spOrder;
    }

    /**
     * 查看我的卖单
     * @return
     */
    @PostMapping("/showDataSeller")
    public List<Map> showDataSeller( ){
        CurrentUser user = CommonUtil.getUser() ;
        return spOrderService.showMyOrder2(user.getUsername());

    }
    /**
     * 确认收货
     * @return
     */
    @PostMapping("/shouhuo")
    public void shouhuo( String ID){

        CurrentUser user = CommonUtil.getUser() ;
      spOrderService.shouhuo(user.getUsername(),ID);

    }
    /**
     * 倒计时
     * @return
     */
    @PostMapping("/Time")
    public   Map<String, Long> Time( ){
        Map<String, Long> map=new HashMap<String, Long>();
        CurrentUser user = CommonUtil.getUser() ;
        Timestamp[]  time = spOrderService.Time(user.getUsername());
        Timestamp date = new Timestamp(System.currentTimeMillis()-1000*60*60*30*24*60);

        Timestamp[]  time1 = spOrderService.Time1(user.getUsername(),date);
        if (time1 != null) {
            Timestamp date1 = new Timestamp(System.currentTimeMillis());
            long c;
            long e = 0;
            long a =time1[0].getTime();
            long b = System.currentTimeMillis();
            if (time1.length>1){
                e =e+ time1.length*1000*60*10;
            }

             c= (b-a+e)/1000;
            map.put("Seconds",c);
  return map;
        }
return  null;





    }
    /**
     * 查Idin订单D看我的卖单
     * @return
     */
    @PostMapping("/showDataSelle")
    public List<Map> showDataSeller( String data){

        return spOrderService.showMyOrder3(data);

    }

    /**
     *确认订单
     * @param ID
     * @return
     */
    @PostMapping("/QrOrder")
    public     List<Map> QrOrder (String ID){
        return spOrderService.QrOrder(ID);
    }
    /**
     *收银台
     * @param ID
     * @return
     */
    @PostMapping("/SytOrder")
    public     List<Map> SytOrder (String ID){
        return spOrderService.SytOrder(ID);
    }

    /**
     * 个人中心
     */
    @PostMapping("/Selectmember")
    public List<Map> Selectmember (){
        CurrentUser user = CommonUtil.getUser() ;
        return spOrderService.Selectmember(user.getUsername());
    };

    /**
     * 个人中心佣金
     */
    @PostMapping("/SelectmemberYj")
    public  Integer SelectmemberYj ()
    {
        CurrentUser user = CommonUtil.getUser() ;
        return spOrderService.SelectmemberYj(user.getUsername());
    };

    /**
     * 个人中心
     */
    @PostMapping("/SelectAddress")
    public List<Map> SelectAddress (){
        CurrentUser user = CommonUtil.getUser() ;
        return spOrderService.SelectAddress(user.getUsername());
    };

    /**
     * 我的地址
     */
    @PostMapping("/UpAddress")
    public Boolean UpAddress (String name,String phone,String region,String detailedAddress,String postalCode){
        CurrentUser user = CommonUtil.getUser() ;
        return spOrderService.UpAddress(name,phone,region,detailedAddress,postalCode,user.getUsername());
    };
    /**
     * 重新shangjia
     */
    @PostMapping("/cxsj")
    public Boolean cxsj (String tbgoodsid){
        String a = tbgoodsid;
        SpOrder so=spOrderService.byNum(tbgoodsid);

        tbgoodsid =so.getTbGoodsid();
        spOrderService.cxsjzt(tbgoodsid);
        SpOrder spOrder = new SpOrder();
        String userName = CommonUtil.getUser().getUsername();
        SpGoods spGoods =  spGoodsService.selectId(tbgoodsid);
        //商品数量-1
        spGoodsService.changeNumadd(tbgoodsid);
        spGoodsService.updateto(userName,tbgoodsid);
        spOrder.setId(uuid());
        spOrder.setTbGoodsid(tbgoodsid);
        spOrder.setTbAddtime(new Date());
        spOrder.setTbFilePath(spGoods.getTbGoodsPath());
        spOrder.setTbGoodsState(spGoods.getTbGoodsState());
        spOrder.setTbNumber(uuid());
        spOrder.setTbOrderState(0);
        spOrder.setTbPrice(spGoods.getTbGoodsPrice());
        spOrder.setTbSeller(userName);
        spOrderService.insert1(spOrder);


        return spOrderService.cxsj(a);
    };
    /**
     * 确认收货点击
     */
    @PostMapping("/qrsh")
    public Boolean qrsh (String id){
        CurrentUser user = CommonUtil.getUser() ;
        return spOrderService.qrsh(user.getUsername(),id);
    };
    /**
     * jywc
     * @return
     */
    @PostMapping("/jywc")
    public Boolean jywc (String id){
        return spOrderService.jywc(id);
    };
    /**
     *上次凭证
     * @param
     * @return
     */
    @PostMapping("/Scpzrder")
    public   String  Scpzrder ( String ID, String state,@RequestParam("pz") MultipartFile pz){
        //上传图片
        String fileName = uploadUtil.upload(pz);
        SpOrder spOrder = spOrderService.showlid(ID);
        spOrder.setTbFilePath(fileName);
        spOrder.setTbOrderState(2);
        //更新
        spOrderService.update(spOrder);
        return "成功";
    }
    /**
     *查看支付凭证
     * @param
     * @return
     */
    @PostMapping("/ckzfpz")
    @ResponseBody
    public   String  ckzfpz ( String id){
        //上传图片
        SpOrder spOrder = spOrderService.showlid(id);
        return spOrder.getTbFilePath();
    }
    /**
     *上次凭证
     * @param
     * @return
     */
    @PostMapping("/zfsq")
    public   Map  zfsq ( String TB_BACKCARD, String TB_BACKNAME,String TB_ZFB_USERNAME, String TB_ZFB_NUMBER,@RequestParam("zfb") MultipartFile zfb,@RequestParam("wx") MultipartFile wx){
        Map map = new HashMap();
        //上传图片
        String fileNameZfb = uploadUtil.upload(zfb);
        //上传图片
        String fileNameWx = uploadUtil.upload(wx);
        CurrentUser user = CommonUtil.getUser() ;
        user.setTB_BACKCARD(TB_BACKCARD);
        user.setTB_BACKNAME(TB_BACKNAME);
        user.setTB_ZFB_FILEPATH(fileNameZfb);
        user.setTB_ZFB_NUMBER(TB_ZFB_NUMBER);
        user.setTB_ZFB_USERNAME(TB_ZFB_USERNAME);
        user.setTB_WX_FILEPATH(fileNameWx);
        spOrderService.updateUserZf(user);
        map.put("success",true);
        return map;
    }
    @RequestMapping("getZFPerson")
    @ResponseBody
    public Map getZFPerson(){
        CurrentUser user = CommonUtil.getUser() ;
        Map map = new HashMap();
        map = spOrderService.getZFPerson(user.getId());
        return spOrderService.getZFPerson(user.getId());
    }

    /**
     *佣金流水1
     * @param
     * @return
     */
    @RequestMapping("yjls1")
    public List<Map> yjls1(){
        CurrentUser user = CommonUtil.getUser() ;

        return spOrderService.yjls1(user.getUsername());
    }


    /**
     *体现金额显示
     * @param
     * @return
     */
     @PostMapping("tixianjine")
    public List<Map>  tixianjine (){
        CurrentUser user = CommonUtil.getUser() ;

        return spOrderService.yjls1(user.getUsername());
    };
    /**
     *体现金额显示
     * @param
     * @return
     */
    @PostMapping("tixianjine2")
    public List<Map>  tixianjine2 (){
        CurrentUser user = CommonUtil.getUser() ;
        return spOrderService.yjls1(user.getUsername());
    };
     /**
     *体现
     * @param
     * @return
     */
    @RequestMapping("tixian")
    public Boolean tixian(String TB_BZJ_PRICE){
        CurrentUser user = CommonUtil.getUser() ;
        double bzj = spOrderService.tixian(user.getUsername());
        double yj =Double.parseDouble(TB_BZJ_PRICE);
        if (bzj>yj){
            double yj2 = bzj-yj;
         spOrderService.tixian2(yj2,user.getUsername());
         return true;
        }else {
            return false;
        }
    }
    /**
     *佣金流水
     * @param
     * @return
     */
    @RequestMapping("yjls")
    @ResponseBody
    public boolean yjls(String data1){

        double yj1 =Double.parseDouble(data1);
        String cs = null;

        CurrentUser user = CommonUtil.getUser() ;
        double a =spOrderService.cxyjls(user.getUsername());
        double yj = yj1+a;
        if(50<yj&&yj<100)
        {cs="3";
        }else if(100<yj&&yj<200){
            cs="7";
        }else if(200<yj&&yj<300){
            cs="15";
        }else if(yj>300){
            cs="24";
        }else {
            cs="0";
        }
        return spOrderService.yjls( yj,user.getUsername(),cs);
    }


    /**\
     * 买单卖单数据
     * @return
     */

    /**\
     * pay
     * @return
//     */
//    @Autowired
//    WapPayController wapPayController;
//    @RequestMapping("/pay")
//    public String checkData(String orderId){
//
//        wapPayController.pay();
//    }

    @RequestMapping("/checkData")
    public String checkData(String orderId){
        try {
            spOrderService.checkData(orderId);
        }catch (Exception e){
            return "审核失败";
        }
        return "审核成功";
    }
}
